/*
 * Copyright 2009 Jamie Gennis
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.code.gwt.remoteaction.server;

import com.google.code.gwt.remoteaction.client.Action;
import java.lang.reflect.Field;

/**
 * A class to extract a field value from a class.
 *
 * @author jgennis
 */
class FieldParameterExtractor implements ParameterExtractor {

  protected final Field field;

  /**
   * Initialize a new FieldParameterExtractor instance to extract a given
   * field.
   *
   * @param field the field to extract from the action class
   * @throws IllegalArgumentException if the declaring class of the given field
   *         does not implement the Action interface
   */
  public FieldParameterExtractor(Field field) throws IllegalArgumentException {
    if (!Action.class.isAssignableFrom(field.getDeclaringClass()))
      throw new IllegalArgumentException("The declaring class of the 'field' parameter must " +
          "implement the " + Action.class.getCanonicalName() + " interface");
    this.field = field;
  }

  /**
   * Extract the field from an Action instance.
   *
   * @param action the action instance
   * @return the extracted field
   * @throws IllegalArgumentException if the action instance is not an instance
   *         of the field's declaring class
   */
  public Object extract(Action action) throws IllegalArgumentException {
    try {
      return field.get(action);
    } catch (IllegalAccessException ex) {
      throw new RuntimeException(ex);
    }
  }
}
